package net.mujiwulian.configs.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import net.mujiwulian.view.UserSimple;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Author: fc
 * @Description: 自定义登录参数接受方式和登录返回数据
 * @Date:Create：in 2019/10/1 10:31
 */
public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        //请求参数是json格式
        if (MediaType.APPLICATION_JSON_UTF8_VALUE.equalsIgnoreCase(request.getContentType()) || MediaType.APPLICATION_JSON_VALUE.equalsIgnoreCase(request.getContentType())) {
            ObjectMapper mapper = new ObjectMapper();
            UsernamePasswordAuthenticationToken authRequest = null;
            try (InputStream is = request.getInputStream()) {
                UserSimple userSimple = mapper.readValue(is, UserSimple.class);
                authRequest = new UsernamePasswordAuthenticationToken(userSimple.getUsername(), userSimple.getPassword());
                return this.getAuthenticationManager().authenticate(authRequest);
            } catch (IOException e) {
                e.printStackTrace();
                new UsernamePasswordAuthenticationToken("", "");
                return this.getAuthenticationManager().authenticate(authRequest);
            } finally {
                assert authRequest != null;
                setDetails(request, authRequest);
            }
        } else {
            return super.attemptAuthentication(request, response);
        }
    }

}
